package com.dlc.shop.delivery.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.enums.DeliveryCompanyType;
import com.dlc.shop.bean.model.RefundAddr;
import com.dlc.shop.bean.vo.OutletConfigInfoVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.constants.DeliveryCacheNames;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.delivery.common.dao.OutletConfigMapper;
import com.dlc.shop.delivery.common.model.OutletConfig;
import com.dlc.shop.delivery.common.service.OutletConfigService;
import com.dlc.shop.service.RefundAddrService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 网点配置
 * @author TRACK
 */
@Service
@AllArgsConstructor
public class OutletConfigServiceImpl extends ServiceImpl<OutletConfigMapper, OutletConfig> implements OutletConfigService {

    private final OutletConfigMapper outletConfigMapper;
    private final RefundAddrService refundAddrService;

    @Override
    public void insert(OutletConfig outletConfig) {
        checkInfo(outletConfig);
        outletConfigMapper.insert(outletConfig);
    }

    @Override
    public void update(OutletConfig outletConfig) {
        checkInfo(outletConfig);
        outletConfigMapper.updateById(outletConfig);
    }

    private void checkInfo(OutletConfig outletConfig) {
        if (Objects.nonNull(outletConfig.getOutletConfigId())) {
            OutletConfig dbOutletConfig = outletConfigMapper.selectById(outletConfig.getOutletConfigId());
            if (!Objects.equals(dbOutletConfig.getShopId(), outletConfig.getShopId())) {
                throw new YamiShopBindException("yami.operate.auth");
            }
            if (!PrincipalUtil.isDbPhone(outletConfig.getMobile(), dbOutletConfig.getMobile(), false)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (outletConfig.getMobile().contains(Constant.ASTERISK)) {
                outletConfig.setMobile(dbOutletConfig.getMobile());
            }
        }
        DeliveryCompanyType deliveryCompanyType = DeliveryCompanyType.instance(outletConfig.getDeliveryCompanyType());
        if (Objects.isNull(deliveryCompanyType)) {
            throw new YamiShopBindException("快递公司不存在");
        }
        String tempId = DeliveryCompanyType.getTempId(outletConfig.getDeliveryCompanyType(), outletConfig.getPaperSize());
        if (Objects.isNull(tempId) || StrUtil.isBlank(tempId)) {
            throw new YamiShopBindException("关联面单不存在");
        }
        if (Objects.nonNull(outletConfig.getShopAddrId())) {
            RefundAddr refundAddr = refundAddrService.getById(outletConfig.getShopAddrId());
            if (Objects.isNull(refundAddr)) {
                throw new YamiShopBindException("商家地址不存在");
            }
            outletConfig.setPrintAddr(refundAddr.getProvince() + refundAddr.getCity() + refundAddr.getArea() + refundAddr.getAddr());
        }
        int count = outletConfigMapper.checkIsExist(outletConfig);
        if (count > 0) {
            throw new YamiShopBindException("请勿重复添加相同的快递公司及商家地址");
        }
    }

    @Override
    public void setDefault(Long outletConfigId) {
        OutletConfig outletConfig = getById(outletConfigId);
        if (Objects.isNull(outletConfig)) {
            // 网点信息不存在
            throw new YamiShopBindException("yami.outlet.config.is.null");
        }
        if (Objects.equals(outletConfig.getIsDefault(), 0)) {
            // 设为默认
            outletConfigMapper.cancelDefault(outletConfig.getShopId());
        }
        outletConfigMapper.setDefault(outletConfigId);
    }

    @Override
    @Cacheable(cacheNames = DeliveryCacheNames.OUTLET_CONFIG_LIST_KEY, key = "#shopId")
    public List<OutletConfigInfoVO> listByShopId(Long shopId) {
        List<OutletConfigInfoVO> infoList = DeliveryCompanyType.getInfoList();
        List<OutletConfigInfoVO> outletList = outletConfigMapper.listByShopId(shopId);
        if (CollUtil.isEmpty(outletList)) {
            return infoList;
        }
        Map<Integer, OutletConfigInfoVO> outletMap = outletList.stream().collect(Collectors.toMap(OutletConfigInfoVO::getDeliveryCompanyType, o -> o));
        for (OutletConfigInfoVO outletConfigInfoVO : infoList) {
            OutletConfigInfoVO shopOutletConfig = outletMap.get(outletConfigInfoVO.getDeliveryCompanyType());
            if (Objects.isNull(shopOutletConfig)) {
                continue;
            }
            long defaultCount = shopOutletConfig.getShopAddrList().stream().filter(addr -> Objects.equals(addr.getIsDefault(), 1)).count();
            outletConfigInfoVO.setIsConfig(1);
            outletConfigInfoVO.setIsDefault(defaultCount > 0L ? 1 : 0);
            outletConfigInfoVO.setShopAddrList(shopOutletConfig.getShopAddrList());
        }
        return infoList;
    }

    @Override
    @CacheEvict(cacheNames = DeliveryCacheNames.OUTLET_CONFIG_LIST_KEY, key = "#shopId")
    public void removeCache(Long shopId) {

    }
}
